/* 
 * File:   BlockingQueue.cpp
 * Author: lucia
 * 
 * Created on 31 de octubre de 2014, 16:44
 */

#include "BlockingQueue.h"

BlockingQueue::BlockingQueue() {
    //    this->pushing = false;
}

void BlockingQueue::push(void* data) {

    std::lock_guard<std::mutex> lock(this->mtx);
    this->queue.push(data);

    this->cv.notify_all();
}

void* BlockingQueue::pop() {
//    std::unique_lock<std::mutex> uni_lock(this->mtx);
//        while (this->pushing){
//            cv.wait(uni_lock);
//        }
//
//    while (this->empty()) {
//        cv.wait(uni_lock);
//    }
//
//    void* data = this->queue.front();
//    this->queue.pop();
//
//    return data;
}

void* BlockingQueue::waitAndPop() {
    std::unique_lock<std::mutex> uni_lock(this->mtx);

    cv.wait(uni_lock,[this]{return !this->queue.empty();});

    void* data = this->queue.front();
    this->queue.pop();

    return data;
}

bool BlockingQueue::tryPop(void* data) {
    std::unique_lock<std::mutex> uni_lock(this->mtx);
    if (this->empty()) {
        return false;
    }

    data = this->queue.front();
    this->queue.pop();
    return true;
}

bool BlockingQueue::empty() {
    std::lock_guard<std::mutex> lock(this->mtx);
    return this->queue.empty();
}

int BlockingQueue::size(){
    return this->queue.size();
}

BlockingQueue::~BlockingQueue() {
}

